<template>
  <div class="department-container">
    <div class="app-container">
      <!-- 封装的工具栏组件 -->
      <page-tools>
        <template #left>
          <span>总记录条数：{{ total }}条</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="goEditEcexl">Excel导入</el-button>
          <el-button type="danger" size="small" @click="exportEcexl">Excel导出</el-button>
          <el-button type="primary" size="small" @click="addEmployee">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 表格 -->
      <el-card style="margin-top: 10px;">
        <el-table border :data="employeeList" prop="enableState">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template slot-scope="scope">
              <el-avatar :size="size" :src="scope.row.staffPhoto" @click.native="openQR(scope.row.staffPhoto)">
                <img src="@/assets/common/banner-64.png">
              </el-avatar>
              <!-- <el-avatar :size="size" :src="scope.row.staffPhoto" /> -->
              <!-- <img :src="" style="width: 100px; height: 60px" alt="头像"> -->
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template slot-scope="scope">
              {{ _formatEmployees(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry">
            <template slot-scope="scope">
              {{ _formatTime(scope.row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" prop="enableState">
            <template slot-scope="scope">
              <el-switch
                :value="scope.row.enableState === 1"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="detailEmployee(scope.row)">查看</el-button>
              <el-button type="text" size="small">分配角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination layout="prev, pager, next" :total="total" @current-change="changePage" />
        </div>
      </el-card>
    </div>
    <!-- @close-Dialog="closeDialog" -->
    <!-- 父组件使用.sync修饰绑定的自定义属性，在子组件内部，就只可以直接通过 update:自定义属性名，修改父组件传递的数据 -->
    <!-- 这是一个语法他糖，:show-dialog="showDialog"  @update:show-dialog="val => showDialog = val" 简写 -->
    <!-- 看似是减少了操作，实际上在编译的时候，会自动生成update两个事件 -->
    <AddEmployee :show-dialog.sync="showDialog" />
    <el-dialog
      title="二维码"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <div class="QrcodeClass">
        <canvas ref="myCanvas" />
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 员工相关接口
import { reqGetEmployeeList, delEmployee } from '@/api/employees'
// 枚举静态数据
import EmployeeEnum from '@/api/constant/employees'
// 时间相关方法
import { formatTime } from '@/utils/formatTime'
// 引入新增员工组件
import AddEmployee from './components/add-employee'
// 二维码
import Qrcode from 'qrcode'
export default {
  name: 'Employees',
  components: {
    AddEmployee
  },
  data() {
    return {
      form: {
        page: 1,
        size: 10
      },
      total: 0,
      employeeList: [], // 员工列表数据
      showDialog: false,
      size: 80,
      dialogVisible: false
    }
  },
  mounted() {
    this.hReqGetEmployeeList()
  },
  methods: {
    // 点击弹出二维码
    openQR(staffPhoto) {
      this.dialogVisible = true
      this.$nextTick(() => {
        Qrcode.toCanvas(this.$refs.myCanvas, staffPhoto)
      })
    },
    // 员工详情
    detailEmployee(row) {
      // console.log(row)
      this.$router.push({
        path: '/employees/detail',
        query: { id: row.id }
      })
    },
    // 获取的员工列表数据
    async hReqGetEmployeeList() {
      const { rows, total } = await reqGetEmployeeList(this.form)
      console.log(rows)
      this.total = total
      this.employeeList = rows
    },
    // 聘用形式格式化
    _formatEmployees(type) {
      const hireType = EmployeeEnum.hireType
      // [{ id: 1, value: '正式' }, { id: 2, value: '非正式' }]
      const map = {}
      hireType.forEach(item => {
        map[item.id] = item.value // {1: "正式", 2: "非正式"}
      })
      return map[type]
    },
    // 处理时间格式化
    _formatTime(time) {
      return formatTime(time, 'YYYY-MM-DD')
    },
    // 分页
    changePage(curPage) {
      this.form.page = curPage
      this.hReqGetEmployeeList()
    },
    // 删除员工
    delEmployee(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          await delEmployee(id)
          this.hReqGetEmployeeList()
          this.$message.success('删除成功!')
        } catch (e) {
          this.$message.success('删除失败！')
        }
      }).catch(() => {
      })
    },
    // 新增员工
    addEmployee() {
      this.showDialog = true
    },
    // 点击跳转到 Excel 页面
    goEditEcexl() {
      this.$router.push('/import')
    },
    // 导出 Excel
    exportEcexl() {
      // 采用懒加载，只有在点击的时候才会正式导入
      import('@/vendor/Export2Excel').then(async excel => {
        const tHeader = {
          '手机号': 'mobile',
          '姓名': 'username',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '部门': 'departmentName'
        }
        // 表头
        const header = Object.keys(tHeader)
        // 必须是一个二维数据参数
        // const data = [
        //   ['张三', '18'],
        //   ['李四', '16']
        // ]
        const newArr = []
        // 获取员工列表
        const { rows } = await reqGetEmployeeList(this.form)
        // 遍历数组，得到每一项对象
        rows.forEach(item => {
          // 没循环一次新增一个数组
          const arr = []
          // 拿到对象里的key值和表头里的value值对比，只要相等或者是被包含，就拿到相等的value值，放入新数组里
          Object.keys(item).forEach(key => {
            if (Object.values(tHeader).includes(key)) {
              item['timeOfEntry'] = this._formatTime(item['timeOfEntry'], 'YYYY-MM-DD')
              item['correctionTime'] = this._formatTime(item['correctionTime'], 'YYYY-MM-DD')
              // console.log(item['formOfEmployment'])
              item['formOfEmployment'] = this._formatEmployees(item['formOfEmployment'])
              // console.log(item['formOfEmployment'])
              arr.push(item[key])
            }
          })
          // 把每一轮的数据添加到数组里去，组成一个二维数组
          newArr.push(arr)
        })
        excel.export_json_to_excel({
          header,
          data: newArr,
          filename: '员工列表', // 下载文件的名字
          autoWidth: true, // 是否允许宽度自适应
          bookType: 'xlsx' // 后缀
        })
      })
    }
    // 自组件通知父组件关闭对话框
    // closeDialog(flag) {
    //   this.showDialog = flag
    // }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__header {
  background-color: #409EFF;
}
.QrcodeClass {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
